package captcha

import (
	"net/http"

	"github.com/mojocn/base64Captcha"

	"gitee.com/goframe/lt-collector/libs/libgin"
)

const (
	HeaderKey = "Set-Cap-Key"
)

var (
	globalConfigCharacter = base64Captcha.ConfigCharacter{
		Height: 80,
		Width:  240,
		//模式0=>数字,1=>字母,2=>算术运算,3=>字母+数字
		Mode:               base64Captcha.CaptchaModeArithmetic,
		IsUseSimpleFont:    false,
		ComplexOfNoiseText: 0,
		ComplexOfNoiseDot:  0,
		IsShowHollowLine:   false,
		IsShowNoiseDot:     false,
		IsShowNoiseText:    false,
		IsShowSlimeLine:    false,
		IsShowSineLine:     false,
		CaptchaLen:         0,
	}

	//BodyInstance = new(Body)
)

type Body struct {
	Key string `json:"key" binding:"required"`

	VerifyValue string `json:"verify_value" binding:"required"`

	CapInterface base64Captcha.CaptchaInterface `json:"-"`
}

func (b *Body) GenerateCaptcha() {
	b.Key, b.CapInterface = base64Captcha.GenerateCaptcha(b.Key, globalConfigCharacter)
}

func (b *Body) Verify() bool {
	return base64Captcha.VerifyCaptcha(b.Key, b.VerifyValue)
}

func GenerateHandler() http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		bean := new(Body)
		bean.GenerateCaptcha()
		w.Header().Set(libgin.HeaderAccessControlExposeHeaders, HeaderKey)
		w.Header().Set(HeaderKey, bean.Key)
		w.Header().Set(libgin.HeaderContentType, libgin.MIMEImagePng)
		_, _ = bean.CapInterface.WriteTo(w)
	}
}
